<template>
  <view class="order-detail-page">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-icon">
        <text class="status-emoji">{{ getStatusEmoji(orderDetail.status) }}</text>
      </view>
      <text class="status-text">{{ getStatusText(orderDetail.status) }}</text>
      <text class="status-desc">{{ getStatusDesc(orderDetail.status) }}</text>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">
        <text class="title-icon">📋</text>
        <text class="title-text">订单信息</text>
      </view>
      <view class="info-item">
        <text class="info-label">订单编号</text>
        <text class="info-value selectable" @longpress="copyOrderNo">{{ orderDetail.orderNo }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">下单时间</text>
        <text class="info-value">{{ formatDateTime(orderDetail.createTime) }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">预约时间</text>
        <text class="info-value booking-time">{{ orderDetail.startTime }} - {{ orderDetail.endTime }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">使用时长</text>
        <text class="info-value">{{ orderDetail.duration }}</text>
      </view>
    </view>

    <!-- 商家信息 -->
    <view class="store-section">
      <view class="section-title">
        <text class="title-icon">🏪</text>
        <text class="title-text">商家信息</text>
      </view>
      <view class="store-info">
        <view class="store-details">
          <text class="store-name">{{ orderDetail.storeName }}</text>
        </view>
      </view>
    </view>

    <!-- 房间信息 -->
    <view class="room-section">
      <view class="section-title">
        <text class="title-icon">🎮</text>
        <text class="title-text">房间信息</text>
      </view>
      <view class="room-info">
        <view class="room-images">
          <swiper class="room-swiper" indicator-dots="true" autoplay="false" v-if="orderDetail.roomImages.length > 0">
            <swiper-item v-for="(image, index) in orderDetail.roomImages" :key="index">
              <image class="room-image" :src="image" mode="aspectFill" @tap="previewImage(image)"></image>
            </swiper-item>
          </swiper>
          <image v-else class="room-image" :src="orderDetail.roomImage" mode="aspectFill" @tap="previewImage(orderDetail.roomImage)"></image>
        </view>
        <view class="room-details">
          <text class="room-name">{{ orderDetail.roomName }}</text>
          <view class="room-tags">
            <text class="room-tag category">{{ orderDetail.categoryName }}</text>
            <text class="room-tag package">{{ orderDetail.packageName }}</text>
          </view>
          <text class="room-price">¥{{ orderDetail.packagePrice }}/{{ orderDetail.packageName }}</text>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="cost-section">
      <view class="section-title">
        <text class="title-icon">💰</text>
        <text class="title-text">费用明细</text>
      </view>
      <view class="cost-item">
        <text class="cost-label">房间费用</text>
        <text class="cost-value">¥{{ orderDetail.roomFee }}</text>
      </view>
      <view class="cost-item" v-if="orderDetail.serviceFee && orderDetail.serviceFee > 0">
        <text class="cost-label">服务费</text>
        <text class="cost-value">¥{{ orderDetail.serviceFee }}</text>
      </view>
      <view class="cost-item" v-if="orderDetail.couponMoney && orderDetail.couponMoney > 0">
        <text class="cost-label">优惠券抵扣</text>
        <text class="cost-value discount">-¥{{ orderDetail.couponMoney }}</text>
      </view>
      <view class="cost-divider"></view>
      <view class="cost-total">
        <text class="total-label">实付金额</text>
        <text class="total-value">¥{{ orderDetail.actualAmount }}</text>
      </view>
      <view class="pay-method" v-if="orderDetail.payType">
        <text class="pay-label">支付方式</text>
        <text class="pay-value">{{ getPayTypeText(orderDetail.payType) }}</text>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <!-- <view class="bottom-actions" v-if="hasActions">
      <button v-if="canPay(orderDetail.status)" class="action-button pay-btn" @tap="payOrder">
        立即付款
      </button>
      <button v-if="canRefund(orderDetail.status)" class="action-button refund-btn" @tap="refundOrder">
        申请退款
      </button>
      <button v-if="canCancel(orderDetail.status)" class="action-button cancel-btn" @tap="cancelOrder">
        取消订单
      </button>
      <button class="action-button contact-btn" open-type="contact" @contact="contactService">
        联系客服
      </button>
    </view> -->

    <!-- 底部安全区域 -->
    <!-- <view class="safe-area-bottom" v-if="hasActions"></view> -->
  </view>
</template>

<script>
import request from '@/common/request.js';
import { mapGetters, mapActions, mapState } from 'vuex';

export default {
  name: 'OrderDetail',

  data() {
    return {
      orderId: '',
      orderNo: '',
      orderDetail: {
        id: '',
        orderNo: '',
        status: 0,
        createTime: '',
        startTime: '',
        endTime: '',
        duration: '',
        storeName: '',
        storeAddress: '',
        storeAvatar: '',
        storePhone: '',
        roomName: '',
        roomImage: '',
        roomImages: [],
        packageName: '',
        packagePrice: '0.00',
        categoryName: '',
        roomFee: '0.00',
        serviceFee: '0.00',
        couponMoney: '0.00',
        actualAmount: '0.00',
        payType: ''
      },
      isLoading: false
    };
  },

  computed: {
    hasActions() {
      return this.canCancel(this.orderDetail.status) ||
        this.canPay(this.orderDetail.status) ||
        this.canRefund(this.orderDetail.status);
    },
    ...mapGetters([
      'getGaodeKey',
      'getSiteName',
      'getLocation',
      'getConfig'
    ]),
    ...mapState({
      globalConfig: state => state?.config || {},
      userLocation: state => state?.location || {},
    })
  },

  onLoad(options) {
    console.log('订单详情页面参数:', options);

    this.orderId = options.id || '';
    this.orderNo = options.orderNo || '';

    if (this.orderId) {
      this.loadOrderDetail();
    } else {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载订单详情
    async loadOrderDetail() {
      if (this.isLoading) return;

      try {
        this.isLoading = true;
        uni.showLoading({ title: '加载中...' });

        const response = await request.httpTokenRequest({
          url: '/api/order/orderInfo?order_id=' + this.orderId,
          method: 'get',
        });

        console.log('订单详情响应:', response);

        if (response && response.data && response.data.code === 1) {
          this.orderDetail = this.formatOrderDetail(response.data.data);
        } else {
          throw new Error(response?.data?.msg || response?.message || '获取订单详情失败');
        }

      } catch (error) {
        console.error('加载订单详情失败:', error);
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        uni.hideLoading();
      }
    },

    // 格式化订单详情数据
    formatOrderDetail(data) {
      const roomImages = data.room?.images || [];
      const formattedImages = roomImages.map(img => this.formatImageUrl(img));
      
      return {
        id: data.id,
        orderNo: data.order_sn,
        status: parseInt(data.status),
        createTime: data.createtime * 1000, // 转换为毫秒时间戳
        startTime: data.start_time_text,
        endTime: data.end_time_text,
        duration: this.calculateDuration(data.start_time, data.end_time),
        storeName: data.agent_title || '未知店铺',
        storeAddress: '详细地址待完善', // 接口暂无此字段
        storeAvatar: formattedImages[0] || '/static/images/default-store.jpg',
        storePhone: data.store_phone || '',
        roomName: data.room_name || '未知房间',
        roomImage: formattedImages[0] || '/static/images/default-room.jpg',
        roomImages: formattedImages,
        packageName: data.roompackage?.name || '标准套餐',
        packagePrice: data.roompackage?.money || '0.00',
        categoryName: data.type?.name || '娱乐',
        roomFee: data.money || '0.00',
        serviceFee: '0.00', // 接口暂无此字段
        couponMoney: data.coupon_money || '0.00',
        actualAmount: data.money || '0.00',
        payType: data.pay_type
      };
    },

    // 计算使用时长
    calculateDuration(startTime, endTime) {
      if (!startTime || !endTime) return '';
      
      const start = new Date(startTime * 1000);
      const end = new Date(endTime * 1000);
      const diffHours = Math.ceil((end - start) / (1000 * 60 * 60));
      
      return `${diffHours}小时`;
    },

    // 格式化图片URL
    formatImageUrl(imageUrl) {
      if (!imageUrl) return '/static/images/default-room.jpg';

      if (imageUrl.startsWith('http')) {
        return imageUrl;
      }

      const baseUrl = this.globalConfig?.site_url || '';
      return `${baseUrl}${imageUrl}`;
    },

    // 格式化完整日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return '';

      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待开始',
        2: '进行中',
        3: '已结束',
        4: '退款中',
        5: '已退款',
        6: '已过期'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取状态描述
    getStatusDesc(status) {
      const descMap = {
        0: '请尽快完成支付',
        1: '请按时到店使用',
        2: '正在使用中，请注意时间',
        3: '订单已完成，感谢您的使用',
        4: '退款申请处理中，请耐心等待',
        5: '退款已完成',
        6: '订单已过期，如有疑问请联系客服'
      };
      return descMap[status] || '';
    },

    // 获取状态表情
    getStatusEmoji(status) {
      const emojiMap = {
        0: '💳',
        1: '⏰',
        2: '🎮',
        3: '✅',
        4: '💰',
        5: '✅',
        6: '⏰'
      };
      return emojiMap[status] || '📋';
    },

    // 获取状态样式类
    getStatusClass(status) {
      return `status-${status}`;
    },

    // 获取支付方式文本
    getPayTypeText(payType) {
      const payTypeMap = {
        '1': '微信支付',
        '2': '余额支付'
      };
      return payTypeMap[payType] || '未知支付方式';
    },

    // 是否可以取消
    canCancel(status) {
      return [0, 1].includes(status);
    },

    // 是否可以支付
    canPay(status) {
      return status === 0;
    },

    // 是否可以退款
    canRefund(status) {
      return [1, 2].includes(status);
    },

    // 复制订单号
    copyOrderNo() {
      uni.setClipboardData({
        data: this.orderDetail.orderNo,
        success: () => {
          uni.showToast({
            title: '订单号已复制',
            icon: 'success'
          });
        }
      });
    },

    // 预览图片
    previewImage(current) {
      uni.previewImage({
        current: current,
        urls: this.orderDetail.roomImages.length > 0 ? this.orderDetail.roomImages : [current]
      });
    },

    // 拨打电话
    callStore() {
      if (!this.orderDetail.storePhone) {
        uni.showToast({
          title: '暂无联系电话',
          icon: 'none'
        });
        return;
      }

      uni.makePhoneCall({
        phoneNumber: this.orderDetail.storePhone
      });
    },

    // 取消订单
    async cancelOrder() {
      const result = await uni.showModal({
        title: '确认取消',
        content: '确定要取消这个订单吗？取消后不可恢复。'
      });

      if (!result.confirm) return;

      try {
        uni.showLoading({ title: '处理中...' });

        const response = await request.httpTokenRequest({
          url: '/api/order/cancel',
          method: 'POST',
          data: { order_id: this.orderId }
        });

        if (response && response.data && response.data.code === 1) {
          uni.showToast({
            title: '取消成功',
            icon: 'success'
          });

          // 刷新订单详情
          setTimeout(() => {
            this.loadOrderDetail();
          }, 1000);
        } else {
          throw new Error(response?.data?.msg || '取消失败');
        }
      } catch (error) {
        console.error('取消订单失败:', error);
        uni.showToast({
          title: error.message || '取消失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 支付订单
    payOrder() {
      uni.navigateTo({
        url: `/pages/pay/pay?orderId=${this.orderId}&orderNo=${this.orderDetail.orderNo}&amount=${this.orderDetail.actualAmount}`
      });
    },

    // 申请退款
    async refundOrder() {
      const result = await uni.showModal({
        title: '申请退款',
        content: '确定要申请退款吗？我们会在1-3个工作日内处理。'
      });

      if (!result.confirm) return;

      try {
        uni.showLoading({ title: '处理中...' });

        const response = await request.httpTokenRequest({
          url: '/api/order/refund',
          method: 'POST',
          data: { order_id: this.orderId }
        });

        if (response && response.data && response.data.code === 1) {
          uni.showToast({
            title: '申请成功',
            icon: 'success'
          });

          // 刷新订单详情
          setTimeout(() => {
            this.loadOrderDetail();
          }, 1000);
        } else {
          throw new Error(response?.data?.msg || '申请失败');
        }
      } catch (error) {
        console.error('申请退款失败:', error);
        uni.showToast({
          title: error.message || '申请失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 联系客服
    contactService() {
      // 实现联系客服的逻辑
      console.log('联系客服');
    }
  }
};
</script>

<style scoped lang="scss">
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 200rpx;
}

/* 自定义导航栏 */
.custom-header {
  background: #fff;
  padding-top: var(--status-bar-height, 44rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 999;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
}

.nav-left {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.nav-icon {
  font-size: 36rpx;
  color: #333;
  margin-right: 16rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

/* 订单状态 */
.status-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;
  position: relative;
  overflow: hidden;
}

.status-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10rpx);
}

.status-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 30rpx;
  background: rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 1;
}

.status-emoji {
  font-size: 60rpx;
}

.status-text {
  display: block;
  font-size: 36rpx;
  font-weight: 500;
  color: #fff;
  margin-bottom: 16rpx;
  position: relative;
  z-index: 1;
}

.status-desc {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  position: relative;
  z-index: 1;
}

/* 不同状态的背景色 */
.status-0 {
  background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
  
  .status-text, .status-desc {
    color: #2d3436;
  }
}

.status-1 {
  background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
}

.status-2 {
  background: linear-gradient(135deg, #00b894 0%, #00cec9 100%);
}

.status-3 {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
}

.status-4, .status-5 {
  background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%);
}

.status-6 {
  background: linear-gradient(135deg, #636e72 0%, #2d3436 100%);
}

/* 信息区块 */
.order-info-section,
.store-section,
.room-section,
.cost-section {
  background: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  margin: 0 20rpx 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.title-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}

.title-text {
  flex: 1;
}

/* 订单信息 */
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  min-width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  text-align: right;
}

.info-value.selectable {
  color: #4285f4;
}

.booking-time {
  font-weight: 500;
  color: #e17055;
}

/* 商家信息 */
.store-info {
  display: flex;
  align-items: center;
}

.store-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 16rpx;
  margin-right: 24rpx;
}

.store-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.store-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 12rpx;
}

.store-address {
  font-size: 24rpx;
  color: #999;
}

.store-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  transition: all 0.3s;
}

.action-btn:active {
  background: #e0e0e0;
  transform: scale(0.95);
}

.btn-icon {
  font-size: 32rpx;
}

/* 房间信息 */
.room-info {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.room-images {
  width: 100%;
  height: 300rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.room-swiper {
  width: 100%;
  height: 100%;
}

.room-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.room-details {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.room-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.room-tags {
  display: flex;
  gap: 16rpx;
}

.room-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
}

.room-tag.category {
  background: #74b9ff;
}

.room-tag.package {
  background: #00b894;
}

.room-price {
  font-size: 28rpx;
  color: #e17055;
  font-weight: 500;
}

/* 费用明细 */
.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.cost-label {
  font-size: 28rpx;
  color: #666;
}

.cost-value {
  font-size: 28rpx;
  color: #333;
}

.cost-value.discount {
  color: #e17055;
}

.cost-divider {
  height: 2rpx;
  background: #f0f0f0;
  margin: 20rpx 0;
}

.cost-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.total-label {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.total-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #e17055;
}

.pay-method {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-top: 1rpx solid #f8f8f8;
  margin-top: 20rpx;
}

.pay-label {
  font-size: 28rpx;
  color: #666;
}

.pay-value {
  font-size: 28rpx;
  color: #333;
}

/* 底部操作按钮 -->
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-button {
  flex: 1;
  height: 88rpx;
  border-radius: 50rpx;
  font-size: 32rpx;
  border: none;
  transition: all 0.3s;
}

.action-button:active {
  transform: scale(0.95);
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.pay-btn {
  background: linear-gradient(135deg, #e17055 0%, #d63031 100%);
  color: #fff;
}

.refund-btn {
  background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
  color: #fff;
}

.contact-btn {
  background: linear-gradient(135deg, #00b894 0%, #00cec9 100%);
  color: #fff;
}

.safe-area-bottom {
  height: calc(88rpx + 60rpx + env(safe-area-inset-bottom));
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .room-info {
    flex-direction: column;
  }
  
  .bottom-actions {
    flex-direction: column;
    gap: 16rpx;
  }
  
  .action-button {
    flex: none;
  }
}
</style>